﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Collections;

namespace AlphaSolutionsGP
{
    public partial class frmEventView : Form
    {
        ArrayList staffIDs = new ArrayList(); //used to store the IDs found by looking at person's name/surname
        ArrayList studentIDs = new ArrayList(); //used to store the IDs found by looking at person's name/surname
        private Event anEvent;
        private bool toModify;

        //new Event
        public frmEventView()
        {
            toModify = false;
            anEvent = new Event();
            InitializeComponent();
            cmdEventType.SelectedIndex = 4;//4=General
            comboPriority.SelectedIndex = 1;
            dtEventDate.MinDate = DateTime.Now;
            dtEventDate.Value = DateTime.Now;
            fillInCombo(comboIDStudent, "student_ID", "STUDENT");
            fillInCombo(comboIDStaff, "staff_ID", "STAFF");
        }

        //constructor with modifiable Event
        public frmEventView(Event e)
        {
            toModify = true;
            anEvent = e;
            InitializeComponent();
            printData();
        }

        public frmEventView(int i)
        {
            toModify = false;
            anEvent = new Event();
            InitializeComponent();
            //fillInCombo(comboPriority);
            cmdEventType.SelectedIndex = 2;
            comboPriority.SelectedIndex = 1;
        }

        //method to print details of the event when in modify mode
        private void printData()
        {
            fillInCombo(comboIDStudent, "student_ID", "STUDENT");
            comboIDStudent.Items.Add("");
            comboIDStaff.Items.Add("");
            fillInCombo(comboIDStaff, "staff_ID", "STAFF");
            cmdEventType.SelectedItem = anEvent.EventName;
            comboIDStaff.SelectedItem = anEvent.staffID;
            comboIDStudent.SelectedItem = anEvent.studentID;
            timePiker.Text = anEvent.EventTime;
            comboPriority.SelectedItem = anEvent.Priority;
            txtDescription.Text = anEvent.Description;
            dtEventDate.Value = Convert.ToDateTime(anEvent.Date);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {            
            if (validate())
            {
                if (toModify)
                {
                    //update anEvent with new values
                    //anEvent.EventName = txtEventName.Text;
                    if (!comboIDStudent.SelectedItem.Equals(""))
                    {
                        anEvent.studentID = comboIDStudent.SelectedItem.ToString();
                    }
                    else
                    {
                        anEvent.studentID = "";
                    }
                    if (!comboIDStaff.SelectedItem.Equals(""))
                    {
                        anEvent.staffID = comboIDStaff.SelectedItem.ToString();
                    }
                    else
                    {
                        anEvent.staffID = "";
                    }
                    anEvent.Date = dtEventDate.Text;
                    anEvent.EventTime = timePiker.Text;
                    anEvent.EventName = cmdEventType.SelectedItem.ToString();
                    anEvent.Description = txtDescription.Text;
                    anEvent.Priority = comboPriority.SelectedItem.ToString();

                    //this is where an event has been modified so needs to be put back into the arraylist.
                    anEvent.amendEvent();
                    this.Close();

                }
                //else new event and add
                else
                {
                    Event theEvent = new Event(0, cmdEventType.Text, txtDescription.Text, dtEventDate.Text, timePiker.Text, comboPriority.SelectedItem.ToString(), comboIDStaff.Text, comboIDStudent.Text);
                    try
                    {
                        theEvent.createEvent();
                        this.Close();
                    }
                    catch
                    {
                        MessageBox.Show("Failed to create the diary Event.");
                    }

                }
            }
        }

        private void bntHelp_Click(object sender, EventArgs e)
        {
            MessageBox.Show("You must fill in all the fields except the staff or student ID, only 1 of these must be filled. \nIf you came to this window by modifying an event, remember to check all the details are correct before submitting.\nFinally, remember to refresh the event list when you leave this window. This is done by clicking \"Agenda\"", "WUC Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private bool validate()
        {
            bool flag = true;
            if (comboIDStudent.Text == "" && comboIDStaff.Text == "")
            {
                MessageBox.Show(" Both Staff ID and Student ID must not be blank");
                flag = false;
            }
            if (timePiker.Text == "")
            {
                MessageBox.Show("Time must not be blank and in the format HH:MM:SS");
                flag = false;
            }

            if (txtDescription.Text == "")
            {
                MessageBox.Show("Description cannot be empty");
                flag = false;
            }

            return flag;
        }

        //this method will search for IDs into the student tab given the first name and surname
        private void findIDByName(string firstName, string surname)
        {
            MySqlConnection connection = new MySqlConnection("server=194.81.104.22;" + "User Id=alpha;" + "database=alpha_db;" + "password=bravo;");
            try
            {
                connection.Open();
                MySqlCommand cmd = connection.CreateCommand();
                MySqlDataReader myReader;
                string tempID = "";
                if (surname.Equals("") && !firstName.Equals("")) //if only firstaname is filled in
                {
                    cmd.CommandText = "SELECT ID FROM PERSON WHERE person_name LIKE '" + firstName + "%' ORDER BY ID"; //select student/staff id for the given first name

                }
                else if (!surname.Equals("") && firstName.Equals("")) //if only surname is filled in
                {
                    cmd.CommandText = "SELECT ID FROM PERSON WHERE person_surname LIKE '" + surname + "%' ORDER BY ID"; //select student/staff id for the given surname
                }
                else //if firstaname and surname are filled in
                {
                    cmd.CommandText = "SELECT ID FROM PERSON WHERE person_name LIKE '" + firstName + "%' && person_surname LIKE '" + surname + "%' ORDER BY ID"; //select student id for the given surname
                }
                myReader = cmd.ExecuteReader(); //execute the reader
                while (myReader.Read())
                {
                    tempID = myReader.GetString("ID");
                    if (tempID.StartsWith("2"))
                    {
                        studentIDs.Add(myReader.GetString("ID")); // add the id to the arrylist
                    }
                    else if (tempID.StartsWith("9"))
                    {
                        staffIDs.Add(myReader.GetString("ID")); // add the id to the arrylist
                    }
                }

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Unable to fill table due to the following error:\n\n" + ex.ToString()); //failure message
            }

            finally
            {
                connection.Close(); //close the connection

            }

        }

        //fill in the combo id by retreiveing the results stored into the arraylist
        private void fillInComboIDStudent()
        {
            for (int i = 0; i < studentIDs.Count; i++)
            {
                comboIDStudent.Items.Add(studentIDs[i].ToString());
            }
        }

        private void fillInComboIDStaff()
        {
            for (int i = 0; i < staffIDs.Count; i++)
            {
                comboIDStaff.Items.Add(staffIDs[i].ToString());
            }
        }

        private void clearStaffIDs()
        {
            //clear the staff arraylist
            for (int i = 0; i < staffIDs.Count; i++)
            {
                staffIDs.RemoveAt(i);
            }
        }

        private void clearStudentIDs()
        {
            //clear the student array list
            for (int i = 0; i < studentIDs.Count; i++)
            {
                studentIDs.RemoveAt(i);
            }
        }

        private void comboIDStudent_Leave(object sender, EventArgs e)
        {
            clearStudentIDs();
            txtStudentSearch.Text = "";
        }

        private void comboIDStaff_Leave(object sender, EventArgs e)
        {
            clearStaffIDs();
            txtStaffSearch.Text = "";
        }

        private void txtStudentSearch_Leave(object sender, EventArgs e)
        {
            string[] name = txtStudentSearch.Text.Split(' ');
            string firstName = name[0]; // store the firstname
            string surname;
            if (name.Length > 1)
                surname = name[1];
            else surname = "";

            clearStudentIDs();
            this.comboIDStudent.Items.Clear();//clear staff combo
            findIDByName(firstName, surname); //find all the IDs that matches among the records
            fillInComboIDStudent(); // add the arraylist into the combo
            clearStudentIDs(); //clear staff array lists

            
        }


        //DINAMICALLY FILL IN A DROPDOWN MENU
        private void fillInCombo(ComboBox cb, string column, string table)
        {
            string columnValue = ""; //this will store the column value
            MySqlConnection connection = new MySqlConnection("server=194.81.104.22;" + "User Id=alpha;" + "database=alpha_db;" + "password=bravo;");
            try
            {
                connection.Open();
                MySqlCommand cmd = connection.CreateCommand();
                cmd.CommandText = "SELECT " + column + " FROM " + table + ""; //select the required column from table
                MySqlDataReader myReader = cmd.ExecuteReader(); //execute the reader
                while (myReader.Read())
                {
                    columnValue = myReader.GetString(column); //save the column value
                    cb.Items.Add(columnValue); // add the value to the combo box
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Unable to fill table due to the following error:\n\n" + ex.ToString()); //failure message
            }

            finally
            {
                connection.Close(); //close the connection

            }
        }
        

        private void txtStaffSearch_Leave(object sender, EventArgs e)
        {
            string[] name = txtStaffSearch.Text.Split(' ');
            string firstName = name[0]; // store the firstname
            string surname;
            if (name.Length > 1)
                surname = name[1];
            else surname = "";

            clearStaffIDs();
            this.comboIDStaff.Items.Clear();//clear staff combo
            findIDByName(firstName, surname); //find all the IDs that matches among the records
            fillInComboIDStaff(); // add the arraylist into the combo
            clearStaffIDs(); //clear staff array lists
        }

        private void frmEventView_Load(object sender, EventArgs e)
        {

        }

    }
}
